<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      .container {
        width: 500px;
        height: 500px;
        position: relative;
        border: 1px solid;
      }
      .mask {
        width: 100px;
        height: 100px;
        background-color: cyan;
        opacity: 0.5;
        position: absolute;
        display: none;
      }
    </style>
  </head>
  <body>
    <div class="container">
      <div class="mask"></div>
    </div>
    <script>
      var containerEle = document.querySelector(".container");
      var maskEle = document.querySelector(".mask");
      //默认mask不显示
      //需要鼠标移入 mask显示
      containerEle.onmouseenter = function () {
        maskEle.style.display = "block";
      };
      //再设置鼠标移出mask小时
      containerEle.onmouseleave = function () {
        maskEle.style.display = "none";
      };

      //鼠标在容器里移动额时候  mask跟随鼠标移动
      containerEle.onmousemove = function (e) {
        //获取鼠标的位置 : 获取相对浏览器的位置
        var x = e.clientX;
        var y = e.clientY;
        var posX = x - this.offsetLeft - maskEle.offsetWidth / 2;
        var posY = y - this.offsetTop - maskEle.offsetHeight / 2;
        //

        //
        //最后一步 判断xy轴的极限距离
        //距离左边最大距离
        if (posX <= 0) {
          posX = 0;
        }
        if (posX > containerEle.clientWidth - maskEle.offsetWidth) {
          posX = containerEle.clientWidth - maskEle.offsetWidth;
        }

        //
        //

        if (posY <= 0) {
          posY = 0;
        }
        if (posY > containerEle.clientHeight - maskEle.offsetHeight) {
          posY = containerEle.clientHeight - maskEle.offsetHeight;
        }
        maskEle.style.left = posX + "px";
        maskEle.style.top = posY + "px";
      };
    </script>
  </body>
</html>
